const {
    app,
    BrowserWindow,
    ipcMain,
    dialog,
    globalShortcut,
    Menu,
    powerMonitor
} = require("electron");
const client = require("electron-connect").client;
const DataStore = require('./render/utils/store')

const myStore = new DataStore({
    name: 'MusicLists'
})
// userData 储存你应用程序设置文件的文件夹，默认是 appData 文件夹附加应用的名称
console.log(app.getPath('userData'))

let isShow = false
let ctrlIndex = 0
class Appwindow extends BrowserWindow {
    constructor(config, file) {
        const base = {
            width: 800,
            height: 600,
            webPreferences: {
                nodeIntegration: true,
                // 在electron 10.0.0之后，remote模块默认关闭
                // 必须手动设置webPreferences中的enableRemoteModule为true之后才能使用
                enableRemoteModule: true, // 这里是关键设置
            },
            show: false
        }
        const finalConfig = Object.assign(base, config)
        // const finalConfig = {...base, ...config}
        super(finalConfig)
        // 加载页面
        this.loadFile(file)

        // ready to show
        this.once('ready-to-show', () => {
            this.show()
        })
        // 配合electron-connect 热加载
        client.create(this)
    }
}

let mainWindow;

function createWindow() {
    // Create the browser window.
    mainWindow = new Appwindow({}, "./render/index.html")

    mainWindow.webContents.on('did-finish-load', () => {
        // 每当electron重启之后, 加载本地存储的内容
        mainWindow.send('getItems', myStore.getItems())
    })

    // 打开调式工具
    // mainWindow.webContents.openDevTools()

    mainWindow.on("closed", function () {

        mainWindow = null;
    });

    // 注册全局快捷键
    registerGlobalCtrls(mainWindow)

    // 初始化菜单
    initMenu(mainWindow)
    MonitorPower(mainWindow)

    let secondWindow = null
    // 创建添加音乐的窗口
    ipcMain.on('add-music-window', () => {
        secondWindow = new Appwindow({
            width: 500,
            height: 400,
            parent: mainWindow
        }, './render/add.html')
    })

    // 调用dialog组件
    ipcMain.on('open-music-dialog', (event) => {
        // console.log('open music dialog')
        dialog.showOpenDialog({
            properties: ['openFile', 'multiSelections'],
            filters: [{
                name: 'musics',
                extensions: ['mp3']
            }, ]
        }).then((files) => {
            if (files) {
                event.sender.send('selected-files', files.filePaths)
            }
        })
    })

    // 接收添加窗口返回的paths数据
    ipcMain.on('add-items', (event, args) => {
        const updateItems = myStore.addItem(args).getItems()
        // console.log(updatedItems)
        mainWindow.send('getItems', updateItems)
        secondWindow.close()
    })

    // 接收删除id数据
    ipcMain.on('delete-item', (event, args) => {
        const updateItems = myStore.deleteItem(args).getItems()
        mainWindow.send('getItems', updateItems)
    })
}

// 监听电源的状态
const MonitorPower = (win) => {
    powerMonitor.on('on-battery', () => {
        win.send('power-battery')
    })
    powerMonitor.on('on-ac', () => {
        win.send('power-ac')
    })
}

const initMenu = (win) => {
    const isMac = process.platform === 'darwin'

    const template = [
        // { role: 'appMenu' }
        ...(isMac ? [{
            label: app.name,
            submenu: [{
                    role: 'about'
                },
                {
                    type: 'separator'
                },
                {
                    role: 'services'
                },
                {
                    type: 'separator'
                },
                {
                    role: 'hide'
                },
                {
                    role: 'hideothers'
                },
                {
                    role: 'unhide'
                },
                {
                    type: 'separator'
                },
                isMac ? {
                    role: 'close'
                } : {
                    role: 'quit'
                }
            ]
        }] : []),
        {
            label: !isShow ? '暂停' : '继续',
            submenu: [{
                    label: !isShow ? '暂停' : '继续',
                    accelerator: 'Space',
                    click: () => {
                        isShow = !isShow
                        initMenu(win)
                        win.send('playorpause')
                    }
                },
                {
                    label: '上一首',
                    accelerator: 'CmdOrCtrl+Left',
                    click: () => {
                        win.send('prev-music')
                    }
                },
                {
                    label: '下一首',
                    accelerator: 'CmdOrCtrl+Right',
                    click: () => {
                        win.send('next-music')
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: '切换模式',
                    accelerator: 'CmdOrCtrl+Shift+M',
                    click: () => {
                        ctrlIndex++
                        if (ctrlIndex === 4) {
                            ctrlIndex = 0
                        }
                        win.send('change-mode', ctrlIndex)
                        initMenu(win)
                    }
                },
                {
                    label: '顺序播放',
                    accelerator: 'CmdOrCtrl+Shift+R',
                    type: 'radio',
                    checked: ctrlIndex === 0,
                    click: () => {
                        ctrlIndex = 0
                        win.send('change-mode', ctrlIndex)
                    }
                },
                {
                    label: '随机播放',
                    accelerator: 'CmdOrCtrl+Shift+S',
                    type: 'radio',
                    checked: ctrlIndex === 1,
                    click: () => {
                        ctrlIndex = 1
                        win.send('change-mode', ctrlIndex)
                    }
                },
                {
                    label: '单曲播放',
                    accelerator: 'CmdOrCtrl+Shift+D',
                    type: 'radio',
                    checked: ctrlIndex === 2,
                    click: () => {
                        ctrlIndex = 2
                        win.send('change-mode', ctrlIndex)
                    }
                },
                {
                    label: '列表循环',
                    accelerator: 'CmdOrCtrl+Shift+L',
                    type: 'radio',
                    checked: ctrlIndex === 3,
                    click: () => {
                        ctrlIndex = 3
                        win.send('change-mode', ctrlIndex)
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: '增加音量',
                    accelerator: 'CmdOrCtrl+Up',
                    click: () => {
                        win.send('up-volume')
                    }
                },
                {
                    label: '减小音量',
                    accelerator: 'CmdOrCtrl+Down',
                    click: () => {
                        win.send('down-volume')
                    }
                },
                {
                    label: '静音',
                    accelerator: 'CmdOrCtrl+M',
                    click: () => {
                        win.send('mute-volume')
                    }
                },
            ]
        },
        {
            label: '查看',
            submenu: [{
                    role: 'reload'
                },
                {
                    role: 'forceReload'
                },
                {
                    type: 'separator'
                },
                {
                    role: 'toggleDevTools'
                },
                {
                    type: 'separator'
                },
                {
                    role: 'togglefullscreen'
                }
            ]
        },
        {
            label: '编辑',
            role: 'editMenu'
        },
        {
            label: '帮助',
            submenu: [{
                label: '星城哈哈',
                click: async () => {
                    const {
                        shell
                    } = require('electron')
                    await shell.openExternal('https://www.xcooo.cn')
                }
            }]
        },
    ]

    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
}

function registerGlobalCtrls(win) {
    // 下一首, 全局快捷键
    globalShortcut.register('CommandOrControl+Shift+Right', () => {
        win.send('next-music')
    })

    // 上一首, 全局快捷键
    globalShortcut.register('CommandOrControl+Shift+Left', () => {
        win.send('prev-music')
    })

    // 暂停或播放, 全局快捷键
    globalShortcut.register('CommandOrControl+Option+M', () => {
        win.send('playorpause')
    })

    // 模式切换, 全局快捷键
    globalShortcut.register('CommandOrControl+Shift+Space', () => {
        ctrlIndex++
        if (ctrlIndex === 4) {
            ctrlIndex = 0
        }
        win.send('change-mode', ctrlIndex)
    })

    // 增加音量
    globalShortcut.register('CommandOrControl+Shift+Up', () => {
        win.send('up-volume')
    })

    // 减少音量
    globalShortcut.register('CommandOrControl+Shift+Down', () => {
        win.send('down-volume')
    })

    // 静音
    globalShortcut.register('CommandOrControl+Shift+M', () => {
        win.send('mute-volume')
    })

    // if (!ret) {
    //     console.log('xixiix')
    // }

    // // 检查快捷键是否注册成功
    // console.log(globalShortcut.isRegistered('CommandOrControl+X'))
}

app.on("ready", createWindow);

app.on("window-all-closed", function () {
    if (process.platform !== "darwin") app.quit();
});

app.on("activate", function () {
    if (mainWindow === null) createWindow();
});